package com.dragee.modules.work.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dragee.common.PageUtils;
import com.dragee.common.R;
import com.dragee.common.VerifyParam;
import com.dragee.config.exception.BusinessException;
import com.dragee.constants.AuthConstants;
import com.dragee.modules.sys.entity.SysRole;
import com.dragee.modules.sys.entity.UserEntity;
import com.dragee.modules.sys.service.ISysRoleService;
import com.dragee.modules.sys.service.UserService;
import com.dragee.modules.work.entity.UserExpanderEntity;
import com.dragee.modules.work.po.UserExpanderPo;
import com.dragee.modules.work.service.UserExpanderService;
import com.dragee.utils.LoginUserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Map;



/**
 * 拓客
 *
 * @author tc
 * @email tc@mail.com
 * @date 2023-03-31 16:41:10
 */
@RestController
@RequestMapping("work/userexpander")
@Api(tags = "work - 拓客")
public class UserExpanderController {
    @Autowired
    private UserExpanderService userExpanderService;
    @Autowired
    private UserService userService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 列表
     */
    @GetMapping("list")
    @ApiOperation("拓客列表")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = userExpanderService.queryPage(params);
        return R.ok().put("data", page);
    }


    /**
     * 信息
     */
    @GetMapping("{id}")
    @ApiOperation("拓客信息")
    public R info(@PathVariable("id") String id){
        UserEntity user = userService.getById(id);
        UserExpanderEntity userSeller = userExpanderService.getById(id);
        return R.ok().put("data", new UserExpanderPo(user, userSeller));
    }

    /**
     * 保存
     */
    @PostMapping("saveOrUpdate")
    @ApiOperation("保存或修改拓客")
    public R saveOrUpdate(@RequestBody UserExpanderPo user){
        VerifyParam.notNull(user);
        Long parentId = LoginUserUtil.getLoginUserId();
        user.setParentId(parentId);
        String password = new Sha256Hash(user.getPassword(), AuthConstants.SLAT_PWD).toHex();
        UserEntity userEntity = null;
        // 添加到用户表
        if (user.getUserId() == null) {
            // 新增
            //用户名唯一性校验
            int count = userService.count(new QueryWrapper<UserEntity>().eq("username", user.getUsername()));
            if (count!=0){
                throw new BusinessException(502,"用户名已存在");
            }
            user.setPassword(password);
            userEntity = new UserEntity(user);
            userService.save(userEntity);
            user.setUserId(userEntity.getUserId());
            userExpanderService.save(new UserExpanderEntity(user));
            // 用户角色关联表插入
            SysRole role = sysRoleService.getOne(new QueryWrapper<SysRole>().eq("role_name", "拓客"), false);
            if (role != null) {
                jdbcTemplate.execute("insert into sys_user_role (user_id, role_id) values ("+user.getUserId()+","+role.getRoleId()+")");
            }
        } else {
            // 修改
            int count = userService.count(new QueryWrapper<UserEntity>()
                    .ne("userId", user.getUserId())
                    .eq("username", user.getUsername()));
            if (count!=0) {
                throw new BusinessException(502,"用户名已存在");
            }
            userEntity = new UserEntity(user);
            userService.saveOrUpdate(userEntity);
            userExpanderService.saveOrUpdate(new UserExpanderEntity(user));
        }
        return R.ok();
    }


    /**
     * 删除
     */
    @GetMapping("delete-by-id")
    @ApiOperation("拓客删除")
    public R delete( String id){
        userExpanderService.removeById(Long.parseLong(id));
        userService.removeById(Long.parseLong(id));
        jdbcTemplate.execute("delete from sys_user_role where user_id = " + id);
        return R.ok();
    }

    @GetMapping("delete-by-ids")
    @ApiOperation("拓客批量删除")
    public R deletes(String ids){
        String[] idArr = ids.split(",");
        Arrays.stream(idArr).forEach(id -> {
            userExpanderService.removeById(Long.parseLong(id));
                    userService.removeById(Long.parseLong(id));
                    jdbcTemplate.execute("delete from sys_user_role where user_id = " + id);
                }
        );
        return R.ok();
    }

}
